import os

from alipay import AliPay
from django import http
from django.conf import settings
from django.db import DataError
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views.generic.base import View

from .models import OrderInfo, Payment
from mgproject.utils.views import LoginRequiredJSONMixin
import json

class PaymentStatusView(LoginRequiredJSONMixin,View):
    def get(self,request):
        """
        查询并保存支付结果
        :param request:
        :return:
        """
        # 接收参数
        params_dict = request.GET.dict()

        # 校验参数（验证签名：判断当前是否支付宝平台重定向过来的请求）
        sign = params_dict.pop('sign')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem")).read(),
            alipay_public_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem")).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        flag = alipay.verify(params_dict,sign)

        if flag:  # 正常请求

            # 获取订单号
            order_id = params_dict.get('out_trade_no')
            # 获取支付宝交易流水号
            trade_no = params_dict.get('trade_no')
            # 保存支付结果
            try:
                Payment.objects.create(order_id=order_id,trade_id=trade_no)
            except DataError:
                return http.HttpResponseForbidden('保存支付结果失败')
            # 更新订单表中支付状态
            OrderInfo.objects.filter(order_id=order_id,status=1).update(status=2)

            # 响应页面结果
            return render(request,'payment/pay_success.html',{'trade_no':trade_no})

        else:
            return http.HttpResponseForbidden('非正常请求')




class PaymentView(LoginRequiredJSONMixin,View):
    def post(self,request):
        """
        获取支付宝支付扫码链接地址
        :param request:
        :return:
        """
        # 接收参数 '{"k":"v"}'  ---> {"k":"v"}
        params_str = request.body.decode()
        # 校验参数
        if not params_str:
            return JsonResponse({'code':4001,'errormsg':'缺少必传参数'})

        dict_params = json.loads(params_str)
        article_id = dict_params['article_id']
        pay_method = dict_params['pay_method']
        total_amount = dict_params['pay_amount']

        # 生成订单

        user = request.user
        # 生成订单编号：年月日时分秒+用户编号
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%03d' % user.id)
        try:
            order = OrderInfo.objects.create(order_id=order_id,user=user,pay_method=pay_method,total_amount=total_amount,article_id=article_id)
        except DataError:
            return JsonResponse({'code':4002,'errormsg':'生成订单失败'})

        # 调用支付接口获取支付链接地址
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem")).read(),
            alipay_public_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem")).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="芒果头条%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
            notify_url=settings.ALIPAY_RETURN_URL
        )


        # 响应结果
        # 响应登录支付宝链接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return JsonResponse({'code': 200, 'errormsg': 'OK', 'alipay_url': alipay_url})